package gupao.concurrency.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class SimpleDeadLockSample {
    static Lock workLock = new ReentrantLock();
    static Lock sleepLock = new ReentrantLock();

    public static void workAndSleep() {
        //一次性获取
        /*if( workLock.tryLock() && sleepLock.tryLock()) {
            try {
                //do sleep
                //work
            }finally {
                workLock.unlock();
                sleepLock.unlock();
            }
        }*/

        workLock.lock();
        try{
            log.info("do some work");
            //主动释放
            if(sleepLock.tryLock()){
                try{
                    //...
                }finally {
                    sleepLock.unlock();
                }
            }

            /*sleepLock.lock();
            try{
                log.info("have some sleep");
            }finally {
                sleepLock.unlock();
            }*/
        }finally {
            workLock.unlock();
        }
    }

    public static void sleepAndWork() {
        sleepLock.lock();
        try{
            log.info("have some sleep");
            workLock.lock();
            try{
                log.info("do some work");
            }finally {
                workLock.unlock();
            }
        }finally {
            sleepLock.unlock();
        }
    }
}
